﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using EPiServer.Framework.Localization;
using EPiServer.Shell;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Shell.ObjectEditing.EditorDescriptors;
using EPiServer.SpecializedProperties;
using OpenWaves.EPiServer.VideoProperty.Dialogs;
using OpenWaves.Video;
using OpenWaves.Web;

namespace OpenWaves.EPiServer.VideoProperty
{
    [EditorDescriptorRegistration(TargetType = typeof (global::EPiServer.Url), UIHint = VideoProperty.UIHint)]
    public class PropertyVideoEditorDescriptor : EditorDescriptor
    {
        public PropertyVideoEditorDescriptor()
        {
            ClientEditingClass = "ow-epi-videoProperty.widgets.VideoUrlSelector";
        }

        public override void ModifyMetadata(ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
        {
            base.ModifyMetadata(metadata, attributes);


            metadata.EditorConfiguration.Add("videoInfoControllerUrl",
                                             Paths.ToResource(typeof (VideoInfoController), "videoInfo"));

            string dialogUrl = AssemblyResourceVirtualPathProvider.CreateUrl(typeof (VideoPreviewDialog)).ToString();
            var control = new Control();
            dialogUrl = control.ResolveUrl(dialogUrl);
            metadata.EditorConfiguration.Add("videoPreviewDialogUrl", dialogUrl);

            metadata.EditorConfiguration.Add("clearButtonText", LocalizationService.Current.GetString("/videoProperty/clearButton", "Clear"));
            metadata.EditorConfiguration.Add("emptyMessage", LocalizationService.Current.GetString("/videoProperty/emptyMessage", "Please enter video url below."));

            var propertyUrl = metadata.Model as PropertyUrl;
            if (propertyUrl == null)
            {
                return;
            }

            string videoUrl = propertyUrl.Url.ToString();
            var videoWebsiteApi = ServiceLocator.Resolve<IVideoWebsiteApi>();


            IVideo videoMetaData = videoWebsiteApi.GetVideo(videoUrl);
            if (videoMetaData != null)
            {
                var selectedVideoUrl = new {key = videoUrl, value = videoMetaData.GetThumbnailForSize(400, 320).Url};
                metadata.EditorConfiguration.Add("selectedVideoUrl", selectedVideoUrl);
            }
        }
    }
}